package v1

import (
	"backend/models"
	"backend/pkg/e"
	"backend/pkg/logging"
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"net/http"
	"runtime"
)

func GetTags(c *gin.Context) {
	name := c.Query("name")
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	if name != "" {
		maps["name"] = name
	}

	stat := c.GetInt("stat")
	if stat != 0 {
		maps["stat"] = stat
	}
	code := e.SUCCESS
	data["lists"] = models.GetTags(1, 10, maps)
	data["total"] = models.GetTagTotal(maps)
	c.JSON(e.SUCCESS, gin.H{
		"code": code,
		"msg":  e.GetMsg(e.SUCCESS),
		"data": data,
	})
}

func AddTag(c *gin.Context) {
	ccopy := c.Copy()
	go func(cc *gin.Context) {
		name := c.Query("name")
		stat := com.StrTo(c.DefaultQuery("stat", "0")).MustInt()
		createdBy := c.Query("created_by")

		valid := validation.Validation{}
		valid.Required(name, "name").Message("名称不能为空")
		valid.MaxSize(name, 10, "name").Message("名称最长10个字符")
		valid.Range(stat, 0, 1, "stat").Message("状态只能是0-1")
		code := e.INVALID_PARAMS
		if !valid.HasErrors() {
			if !models.ExistTagByName(name) {
				code = e.SUCCESS
				models.AddTag(name, stat, createdBy)
			} else {
				code = e.ERROR
			}
		} else {
			for _, err := range valid.Errors {
				logging.Fatal(err.Key, err.Message)
			}
		}
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  e.GetMsg(code),
			"data": make(map[string]string),
		})

		runtime.Gosched()
	}(ccopy)
}

func EditTag(c *gin.Context) {
	ch := make(chan int, 9)
	ch2 := make(chan int, 10)
	go func() {
		for i := 1; i < 10; i++ {
			ch <- i
		}
	}()

	go func() {
		for i := 1; i < 10; i++ {
			tmp := <-ch
			ch2 <- tmp
		}
	}()

	c.String(200, "%d", len(ch2))
}

func DeleteTag(c *gin.Context) {

}
